package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.entity.excel.CustomerExcelEntity;
import one.stand.enums.CustomerStateEnums;
import one.stand.enums.EnumUtil;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CustomerRequest;
import one.stand.request.FollowRecordRequest;
import one.stand.request.InputDealMoneyRequest;
import one.stand.response.CompanyCustomerLableResponse;
import one.stand.response.CustomerResponse;
import one.stand.response.FollowRecordResponse;
import one.stand.response.GetCustomerInfoResponse;
import one.stand.service.BaseService;
import one.stand.service.BusinessCardService;
import one.stand.service.CustomerService;
import one.stand.service.FollowRecordService;
import one.stand.service.impl.checkparam.CustomerServiceCheckParam;
import one.stand.util.ExportDataDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class CustomerServiceImpl extends BaseService implements CustomerService {
    @Autowired
    private BusinessCardService businessCardService;
    @Autowired
    private FollowRecordService followRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> addCustomer(CustomerRequest request) {
        log.info("存为客户信息：{}", JSON.toJSONString(request));
        if (CustomerServiceCheckParam.add(request)) {
            return ResultModel.checkParamFail();
        }
        //添加客户记录
        CustomerModel customerModel = new CustomerModel();
        BeanUtils.copyProperties(request, customerModel);
        customerModel.setAscriptionId(request.getMyCardId().longValue());
        customerModel.setIsDel(0);
        customerModel.setCreateTime(new Date());
        customerModel.setCompanyId(request.getCId());
        customerModel.setCustomerRemark(request.getCustomerRemark());
        customerModel.setTurnoverAmount(null);
        customerMapper.insertSelective(customerModel);

        // 查询员工本月成交金额和客户数计划
        UserTaskModel userTaskModel1 = userTaskMapper.select(new UserTaskModel() {{
            setCardId(request.getMyCardId().intValue());
            setCreateTime(new Date());
        }});
        if (userTaskModel1 != null) {
            // 更改员工本月目标状态
            UserTaskModel userTaskModel = new UserTaskModel();
            if (userTaskModel1.getCompleteTargetAmount() >= userTaskModel1.getTargetAmount()
                    && (userTaskModel1.getCompleteCustomerNum() + 1) >= userTaskModel1.getCustomerNum()) {
                userTaskModel.setCompletionStatus(2);
            }
            userTaskModel.setCompleteCustomerNum(userTaskModel1.getCompleteCustomerNum() + 1);
            userTaskModel.setTaskId(userTaskModel1.getTaskId());
            userTaskMapper.updateByPrimaryKeySelective(userTaskModel);
        }
        //添加标签
        if (request.getLableIds() != null) {
            request.setCustomerId(customerModel.getCustomerId());
            updCustomerLabel(request);
        }
        //添加跟进记录
        JSONObject jsonObject = new JSONObject();
        if (request.getEntrance() == 1) {
            jsonObject.put("data", "手动添加为客户");
        } else {
            jsonObject.put("data", "存为客户");
        }
        jsonObject.put("type", 3);
        FollowRecordRequest recordRequest = new FollowRecordRequest();
        recordRequest.setCardId(customerModel.getCardId().intValue());
        recordRequest.setId(request.getId());
        recordRequest.setMyCardId(request.getMyCardId());
        recordRequest.setFollowRemark(jsonObject.toJSONString());
        followRecordService.addFollow(recordRequest);

        if (request.getTurnoverAmount() != null) {
            InputDealMoneyRequest moneyRequest = new InputDealMoneyRequest();
            moneyRequest.setCustomerId(customerModel.getCustomerId());
            moneyRequest.setId(request.getId());
            moneyRequest.setCId(request.getCId());
            moneyRequest.setRemark(request.getRemark());
            moneyRequest.setMoney(request.getTurnoverAmount());
            moneyRequest.setMyCardId(recordRequest.getMyCardId());
            inputDealMoney(moneyRequest);
        }
        return ResultModel.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> manualAdd(CustomerRequest request) {
        log.info("手动添加客户：{}", JSON.toJSONString(request));
        if (StringUtils.isBlank(request.getPersonalWx()) && StringUtils.isBlank(request.getPhone())) {
            log.info("请输入手机号码~！:", request);
            return ResultModel.fail("请输入手机号码~！");
        }
        BusinessCardModel model = businessCardMapper.selectMyCard(new BusinessCardModel() {{
            setPersonalWx(request.getPersonalWx());
            setPhone(request.getPhone());
            setCompanyId(request.getCId().intValue());
            setIsDel(0);
            setState(1);
        }});
        Map<String, Object> map = new HashMap<>(4);
        if (model != null) {
            log.info("该用户是本公司员工，不能添加为客户!", model);
            map.put("type", "1");
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }
        BusinessCardModel businessCardModel = businessCardMapper.selectRepeatInfo(new BusinessCardModel() {{
            setPersonalWx(request.getPersonalWx());
            setPhone(request.getPhone());
            setCompanyId(request.getCId().intValue());
        }});
        if (businessCardModel != null && businessCardModel.getCustomerState() == 1) {
            log.info("该客户已被成员" + businessCardModel.getName() + "独占，请与他取得联系~！", businessCardModel);
            map.put("type", "2");
            map.put("data", businessCardModel.getName());
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }
        if (businessCardModel != null && businessCardModel.getCustomerState() == 2) {
            log.info("共享客户池已存在该客户，前去抢为独占~！", businessCardModel);
            map.put("type", "3");
            map.put("data", businessCardModel.getCardId() + "");
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }

        BusinessCardRequest cardRequest =new BusinessCardRequest();
        BeanUtils.copyProperties(request,cardRequest);
        cardRequest.setCId(request.getCId());
        cardRequest.setCompanyId(0);
        // 客户名片（公司成员创建）
        cardRequest.setState(2);
        ResultModel<Integer> resultModel = businessCardService.manualAdd(cardRequest);
        if (!resultModel.isSuccess()) {
            log.info(resultModel.getMessage(), businessCardModel);
            return ResultModel.fail(resultModel.getMessage());
        }
        //标识内部进入
        if (request.getEntrance() == null) {
            request.setEntrance(1);
        }
        request.setCardId(resultModel.getData());
        try {
            if (CustomerServiceCheckParam.add(request)) {
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //添加为客户
        ResultModel resultModel1 = addCustomer(request);
        return resultModel1;
    }

    @Override
    public ResultModel<List<CustomerResponse>> getCustomer(CustomerRequest request, boolean fal) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CustomerModel model = new CustomerModel();
        if (request.getCustomerState() == null || request.getCustomerState() == 4) {
            request.setCustomerState(null);
        }
        BeanUtils.copyProperties(request, model);
        // 查询登录人的客户
        if (request.getCustomerState() != null && request.getCustomerState() != 2 && "1".equals(request.getType() + "")) {
            if (request.getCardId() != null) {
                model.setAscriptionId(request.getCardId().longValue());
            } else {
                model.setAscriptionId(request.getMyCardId().longValue());
            }
        }
        model.setIsDel(0);
        model.setLabelIds(request.getLableIds());
        model.setCompanyId(request.getCId());
        if (fal) {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
        }
        List<CustomerModel> modelList = customerMapper.getCustomer(model);
        if (fal) {
            PageInfo<CustomerModel> pageInfo = new PageInfo(modelList);
            List<CustomerResponse> responseList = new ArrayList<>();
            pageInfo.getList().forEach(m -> {
                CustomerResponse response = new CustomerResponse();
                BeanUtils.copyProperties(m, response);
                List<CompanyCustomerLableModel> companyCustomerLableModel = m.getLableModelList();
                List<CompanyCustomerLableResponse> lableResponseList = new ArrayList<>();
                companyCustomerLableModel.forEach(c -> {
                    CompanyCustomerLableResponse r = new CompanyCustomerLableResponse();
                    BeanUtils.copyProperties(c, r);
                    lableResponseList.add(r);
                });
                response.setResponseList(lableResponseList);
                if (null != m.getRecordModel()) {
                    FollowRecordResponse recordResponse = new FollowRecordResponse();
                    BeanUtils.copyProperties(m.getRecordModel(), recordResponse);
                    response.setRecordResponse(recordResponse);
                }
                responseList.add(response);
            });
            return ResultModel.success(responseList);
        } else {
            List<CustomerResponse> responseList = new ArrayList<>();
            modelList.forEach(m -> {
                CustomerResponse response = new CustomerResponse();
                BeanUtils.copyProperties(m, response);
                List<CompanyCustomerLableModel> companyCustomerLableModel = m.getLableModelList();
                List<CompanyCustomerLableResponse> lableResponseList = new ArrayList<>();
                StringBuffer lable = new StringBuffer();
                companyCustomerLableModel.forEach(c -> {
                    CompanyCustomerLableResponse r = new CompanyCustomerLableResponse();
                    BeanUtils.copyProperties(c, r);
                    lableResponseList.add(r);
                    lable.append(c.getLableName()).append(",");
                });
                response.setLable(StringUtils.isBlank(lable + "")?"":lable.substring(0,lable.length() - 1));
                response.setResponseList(lableResponseList);
                if (null != m.getRecordModel()) {
                    FollowRecordResponse recordResponse = new FollowRecordResponse();
                    BeanUtils.copyProperties(m.getRecordModel(), recordResponse);
                    response.setRecordResponse(recordResponse);
                }
                responseList.add(response);
            });
            return ResultModel.success(responseList);
        }
    }

    @Override
    public ResultModel<Map<String, Object>> getCustomerPC(CustomerRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CustomerModel model = new CustomerModel();
        if (request.getCustomerState() == null || request.getCustomerState() == 4) {
            request.setCustomerState(null);
        }
        BeanUtils.copyProperties(request, model);
        // 查询登录人的客户
        if (request.getCustomerState() != null && request.getCustomerState() != 2) {
            if (request.getCardId() != null) {
                model.setAscriptionId(request.getCardId().longValue());
            } else {
                model.setAscriptionId(request.getMyCardId().longValue());
            }
        }
        model.setIsDel(0);
        model.setLabelIds(request.getLableIds());
        model.setCompanyId(request.getCId());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CustomerModel> modelList = customerMapper.getCustomer(model);
        List<CustomerResponse> responseList = new ArrayList<>();
        modelList.forEach(m -> {
            CustomerResponse response = new CustomerResponse();
            BeanUtils.copyProperties(m, response);
            List<CompanyCustomerLableModel> companyCustomerLableModel = m.getLableModelList();
            List<CompanyCustomerLableResponse> lableResponseList = new ArrayList<>();
            companyCustomerLableModel.forEach(c -> {
                CompanyCustomerLableResponse r = new CompanyCustomerLableResponse();
                BeanUtils.copyProperties(c, r);
                lableResponseList.add(r);
            });
            response.setResponseList(lableResponseList);
            if (null != m.getRecordModel()) {
                FollowRecordResponse recordResponse = new FollowRecordResponse();
                BeanUtils.copyProperties(m.getRecordModel(), recordResponse);
                response.setRecordResponse(recordResponse);
            }
            responseList.add(response);
        });
        PageInfo<CustomerModel> pageInfo = new PageInfo(modelList);
        Map<String, Object> map = new HashMap<>(2);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<ExportDataDTO<CustomerExcelEntity>> getCustomerExport(CustomerRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        List<CustomerResponse> list = getCustomer(request, false).getData();
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CustomerExcelEntity> excelEntities = new ArrayList<>();
        list.forEach(customerResponse -> {
            {
                CustomerExcelEntity excelEntity = new CustomerExcelEntity();
                BeanUtils.copyProperties(customerResponse, excelEntity);
                excelEntity.setTurnoverAmount(getMoneyString(customerResponse.getTurnoverAmount() + ""));
                excelEntities.add(excelEntity);
            }
        });
        ExportDataDTO exportDataDTO = new ExportDataDTO();
        exportDataDTO.setSheetName("客户列表");
        exportDataDTO.setFileName("客户列表");
        exportDataDTO.setTitle("客户列表");
        exportDataDTO.setDataList(excelEntities);
        return ResultModel.success(exportDataDTO);
    }

    @Override
    public ResultModel selectCustomerList(CustomerRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        CustomerModel model = new CustomerModel();
        model.setAscriptionId(request.getMyCardId().longValue());
        List<CustomerModel> modelList = customerMapper.selectCustomerList(model);
        PageInfo<CustomerModel> pageInfo = new PageInfo(modelList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel<List<CustomerResponse>> countCustomer(CustomerRequest request) {
        CustomerModel model = new CustomerModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId());
        model.setAscriptionId(request.getMyCardId().longValue());
        List<CustomerModel> modelList = customerMapper.countCustomer(model);
        List<CustomerResponse> responseList = new ArrayList<>();
        modelList.forEach(customerModel -> {
            {
                CustomerResponse response = new CustomerResponse();
                BeanUtils.copyProperties(customerModel, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<GetCustomerInfoResponse> getCustomerInfo(Long cardId) {
        GetCustomerInfoResponse response = customerMapper.getCustomerInfo(new CustomerModel() {{
            setCardId(cardId.intValue());
        }});
        if (response == null) {
            return ResultModel.noData();
        }
        List<CompanyCustomerLableModel> modelList = companyCustomerLableMapper.selectCustomerLable(new CompanyCustomerLableModel() {{
            setCustomerId(response.getCustomerId());
        }});
        List<CompanyCustomerLableResponse> responseList = new ArrayList<>();
        modelList.forEach(m -> {
            CompanyCustomerLableResponse lableResponse = new CompanyCustomerLableResponse();
            BeanUtils.copyProperties(m, lableResponse);
            responseList.add(lableResponse);
        });
        response.setLableResponseList(responseList);
        return ResultModel.success(response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> updCustomer(CustomerRequest request) {
        log.info("修改客户：{}", JSON.toJSONString(request));
        BusinessCardModel model = businessCardMapper.select(new BusinessCardModel() {{
            setPersonalWx(request.getPersonalWx());
            setPhone(request.getPhone());
            setCompanyId(request.getCId().intValue());
            setIsDel(0);
            setMyCardId(request.getCardId());
            setState(1);
        }});
        Map<String, Object> map = new HashMap<>(4);
        if (model != null) {
            log.info("该用户是本公司员工，修改失败!", model);
            map.put("type", "1");
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }
        BusinessCardModel businessCardModel = businessCardMapper.selectRepeatInfo(new BusinessCardModel() {{
            setPersonalWx(request.getPersonalWx());
            setPhone(request.getPhone());
            setCompanyId(request.getCId().intValue());
            setMyCardId(request.getCardId());
        }});
        if (businessCardModel != null && businessCardModel.getCustomerState() == 1) {
            log.info("该客户已被成员" + businessCardModel.getName() + "独占，请与他取得联系~！", businessCardModel);
            map.put("type", "2");
            map.put("data", businessCardModel.getName());
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }
        if (businessCardModel != null && businessCardModel.getCustomerState() == 2) {
            log.info("共享客户池已存在该客户，前去抢为独占~！", businessCardModel);
            map.put("type", "3");
            map.put("data", businessCardModel.getCardId() + "");
            return ResultModel.fail(new JSONObject(map).toJSONString());
        }

        BusinessCardRequest cardRequest =new BusinessCardRequest();
        BeanUtils.copyProperties(request,cardRequest);
        cardRequest.setCId(request.getCId());
        cardRequest.setCompanyId(request.getCompanyId().intValue());
        cardRequest.setMyCardId(request.getMyCardId());
        cardRequest.setId(request.getId());
        ResultModel resultModel = businessCardService.updAdd(cardRequest);
        if (!resultModel.isSuccess()) {
            return ResultModel.fail();
        }
        // 修改客户标签
        if (request.getLableIds() != null) {
            updCustomerLabel(new CustomerRequest() {{
                setCustomerId(request.getCustomerId());
                setLableIds(request.getLableIds());
                setId(request.getId());
                setMyCardId(request.getMyCardId());
                setCId(request.getCId());
                setFollowType("1");
            }});
        }
        //修改客户类型
        if (request.getCustomerState() != null) {
            updCustomerState(new CustomerRequest() {{
                setCustomerId(request.getCustomerId());
                setCustomerState(request.getCustomerState());
                setCustomerRemark(request.getCustomerRemark());
                setId(request.getId());
                setMyCardId(request.getMyCardId());
                setCId(request.getCId());
                setFollowType("1");
            }});
        }
        //录入成交金额
        if (null != request.getTurnoverAmount() && request.getTurnoverAmount() > 0) {
            inputDealMoney(new InputDealMoneyRequest() {{
                setCustomerId(request.getCustomerId());
                setMoney(request.getTurnoverAmount());
                setRemark(request.getRemark());
                setId(request.getId());
                setMyCardId(request.getMyCardId());
                setCId(request.getCId());
            }});
        }
        return ResultModel.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> inputDealMoney(InputDealMoneyRequest request) {
        log.info("录入客户成交金额记录：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        boolean fal = request.getInputDealId() == null && (request.getMoney() == null || request.getMoney() <= 0);
        if (fal) {
            return ResultModel.fail("请输入有效金额~！");
        }
        CustomerModel customerModel = customerMapper.selectByPrimaryKey(request.getCustomerId());
        if (customerModel != null && customerModel.getCustomerState() == 1 && customerModel.getAscriptionId() != request.getMyCardId().longValue()) {
            return ResultModel.fail("该客户不是您的独占客户，无法录入成交金额~！");
        }
        InputDealMoneyModel model = new InputDealMoneyModel();
        if(request.getInputDealId() != null) {
            model.setInputDealId(request.getInputDealId());
            model.setPhotos(request.getPhotos());
            inputDealMoneyMapper.updateByPrimaryKeySelective(model);
            return ResultModel.success(true);
        }
        model.setCustomerId(request.getCustomerId());
        model.setInputId(request.getMyCardId());
        model.setCompanyId(request.getCId().intValue());
        model.setMoney(request.getMoney());
        model.setPhotos(request.getPhotos());
        model.setRemark(request.getRemark());
        model.setCreateTime(currentDate());
        model.setIsDel(0);
        if (inputDealMoneyMapper.insertSelective(model) > 0) {
            // 累加客户表成交总额
            CustomerModel customerModel1 = new CustomerModel();
            customerModel1.setCustomerId(request.getCustomerId());
            customerModel1.setTurnoverAmount(request.getMoney());
            customerModel1.setAscriptionId(request.getMyCardId().longValue());
            customerModel1.setCustomerState(1);
            customerMapper.updateTurnoverAmount(customerModel1);
            // 查询员工本月成交金额和客户数计划
            UserTaskModel userTaskModel1 = userTaskMapper.select(new UserTaskModel() {{
                setCardId(request.getMyCardId());
                setCreateTime(new Date());
            }});
            if (userTaskModel1 != null) {
                // 更改员工本月目标状态
                UserTaskModel userTaskModel = new UserTaskModel();
                Integer completeTargetAmount = userTaskModel1.getCompleteTargetAmount() + request.getMoney();
                Integer completeCustomerNum = userTaskModel1.getCompleteCustomerNum();
                if (customerModel.getCustomerState() == 2) {
                    completeCustomerNum++;
                }
                if (completeTargetAmount >= userTaskModel1.getTargetAmount()
                        && completeCustomerNum >= userTaskModel1.getCustomerNum()) {
                    userTaskModel.setCompletionStatus(2);
                }
                userTaskModel.setCompleteCustomerNum(completeCustomerNum);
                userTaskModel.setCompleteTargetAmount(userTaskModel1.getCompleteTargetAmount() + request.getMoney());
                userTaskModel.setTaskId(userTaskModel1.getTaskId());
                userTaskMapper.updateByPrimaryKeySelective(userTaskModel);
            }
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Boolean> delInputDealPhotos(InputDealMoneyRequest request) {
        log.info("删除成交记录表图片：{}", JSON.toJSONString(request));
        if (request == null || request.getInputDealId() == null) {
            return ResultModel.checkParamFail();
        }
        inputDealMoneyMapper.delInputDealPhotos(request.getInputDealId());
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> updCustomerState(CustomerRequest request) {
        try {
            if (request.getCustomerState() == null || request.getCustomerId() == null) {
                return ResultModel.checkParamFail();
            }
            CustomerModel model = customerMapper.selectByPrimaryKey(request.getCustomerId());
            if (null == model) {
                return ResultModel.fail("该用户不存在");
            }
            //如果设置成共享客户 只能本人设置
            if (model.getCustomerState().equals(CustomerStateEnums.MONOPOLY.getCode()) && model.getAscriptionId() != request.getMyCardId().longValue()) {
                return ResultModel.fail("您不能设置为共享客户");
            }
            //如果是独占客户则设置为自己的客户
            model.setAscriptionId(request.getMyCardId().longValue());
            model.setCustomerState(request.getCustomerState());
            model.setCustomerRemark(request.getCustomerRemark());
            customerMapper.updateByPrimaryKeySelective(model);
            // 值1不添加跟进记录：其它要添加跟进记录
            if(!"1".equals(request.getFollowType())) {
                //添加跟进记录
                CustomerStateEnums followTypeEnum = EnumUtil.getByIntegerTypeCode(CustomerStateEnums.class, "getCode", request.getCustomerState() + "");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", "设置为" + followTypeEnum.getMessage());
                jsonObject.put("type", 2);
                FollowRecordRequest recordRequest = new FollowRecordRequest();
                recordRequest.setCardId(model.getCardId());
                recordRequest.setId(request.getId());
                recordRequest.setFollowRemark(jsonObject.toJSONString());
                recordRequest.setMyCardId(request.getMyCardId());
                followRecordService.addFollow(recordRequest);
            }
            return ResultModel.success();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Boolean> updBatchCustomerState(CustomerRequest request) {
        log.info("PC修改客户类型：{}", JSON.toJSONString(request));
        if (request == null || request.getCustomerIds() == null) {
            return ResultModel.checkParamFail();
        }
        CustomerModel model = new CustomerModel();
        model.setIds(request.getCustomerIds().split(","));
        model.setCustomerState(1);
        model.setAscriptionId(request.getMyCardId().longValue());
        customerMapper.updateMoveCustomer(model);
        return ResultModel.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> updCustomerLabel(CustomerRequest request) {
        try {
            CustomerModel model = customerMapper.selectByPrimaryKey(request.getCustomerId());
            if (null == model) {
                return ResultModel.noData();
            }
            if(null==request.getLableIds()){
                request.setLableIds(new Integer[0]);
            }
            List<CompanyCustomerLableModel> lableModelList = companyCustomerLableMapper.selectLibles(request.getLableIds());
            if (request.getLableIds().length != lableModelList.size()) {
                return ResultModel.fail("标签错误");
            }
            CustomerLabelModel customerLabelModel = new CustomerLabelModel();
            customerLabelModel.setCustomerId(model.getCustomerId());
            customerLabelModel.setLableIds(request.getLableIds());
            customerLabelMapper.del(customerLabelModel);
            customerLabelMapper.insertSelective(customerLabelModel);
            // 值为1时不添加跟进记录：其它要添加跟进记录
            if(!"1".equals(request.getFollowType())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", lableModelList);
                jsonObject.put("type", 1);
                //添加跟进记录
                FollowRecordRequest recordRequest = new FollowRecordRequest();
                recordRequest.setCardId(model.getCardId());
                recordRequest.setId(request.getId());
                recordRequest.setFollowRemark(jsonObject.toString());
                recordRequest.setMyCardId(request.getMyCardId());
                followRecordService.addFollow(recordRequest);
            }
            return ResultModel.success();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultModel.fail();
        }
    }

    @Override
    public ResultModel<List<CustomerResponse>> getCustomerList(CustomerRequest request) {
        List<CustomerModel> modelList = customerMapper.getCustomerList(request.getCId().intValue(), request.getName(), request.getMyCardId().intValue());
        List<CustomerResponse> responseList = new ArrayList<>();
        modelList.forEach(m -> {
            CustomerResponse response = new CustomerResponse();
            BeanUtils.copyProperties(m, response);
            responseList.add(response);
        });
        return ResultModel.success(responseList);
    }
}
